<template>
  <div class="doctorList pd-20">
    <el-row>
      <el-col :span="14">
        <el-input v-model="nickName"
                  placeholder="请输入姓名"
                  class="w-200"
                  clearable
                  @clear="handleQuery" />
        <el-date-picker v-model="startTime"
                        type="date"
                        placeholder="开始时间"
                        value-format="yyyy-MM-dd"
                        clearable
                        @change="handleQuery"
                        @clear="handleQuery"></el-date-picker>
        <el-date-picker v-model="endTime"
                        type="date"
                        placeholder="结束时间"
                        value-format="yyyy-MM-dd"
                        clearable
                        @change="handleQuery"
                        @clear="handleQuery"></el-date-picker>
        <el-select v-model="companyId"
                   ref="selectDom"
                   placeholder="请选择所属公司"
                   filterable
                   remote
                   reserve-keyword
                   :remote-method="searchMethod"
                   :loading="loading1"
                   class="w-200"
                   clearable
                   @clear="handleQuery"
                   @change="handleSelect">
          <el-option v-for="item in companyFilterList"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary"
                   @click="handleQuery">查 询</el-button>
      </el-col>
      <el-col :span="4">
        <el-upload :action="fileImportAction"
                   :data="{token:token,'loginId':loginId,'client':commonConst.client}"
                   :on-success="uploadSuccess"
                   accept=".xls,.xlsx"
                   :auto-upload="true"
                   :on-exceed="exceedFile"
                   :before-upload="beforeAvatarUpload">
          <el-button type="primary">
            导 入</el-button>
        </el-upload>
      </el-col>
    </el-row>

    <el-table ref="multipleTable"
              :data="dataList"
              style="width: 100%"
              border
              v-loading="loadingList"
              class="mt-20">
      <el-table-column type="index"
                       label="序号"
                       align="center"
                       width="50">
      </el-table-column>
      <el-table-column label="头像"
                       width="80"
                       align="center">
        <template slot-scope="scope">
          <el-avatar :size="50">
            <el-image :src="scope.row.headImageUrl"
                      :preview-src-list="[scope.row.headImageUrl]">
            </el-image>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="医生">
        <template slot-scope="scope">
          <span style="display: block">登录名: {{scope.row.loginName}}</span>
          <span v-if="scope.row.nickName != ''"
                style="display: block;">昵称: {{scope.row.nickName}} ({{scope.row.positionName}}) </span>
        </template>
      </el-table-column>
      <el-table-column label="专家"
                       width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.isExpert=='0'"
                style="color: #1f262d">非专家</span>
          <span v-if="scope.row.isExpert=='1'"
                style="color: #13ce66">三甲专家</span>
          <span v-if="scope.row.isExpert=='2'"
                style="color: #E6A23C">专科专家</span>
        </template>
      </el-table-column>
      <el-table-column label="性别"
                       width="50"
                       align="center"
                       :formatter="formatterSex">
      </el-table-column>
      <el-table-column label="医院&科室"
                       width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.hospitalName != null"
                style="display: block">{{scope.row.hospitalName}} <br />({{scope.row.departmentName}})</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态"
                       width="80">
        <template slot-scope="scope">
          <el-tag type="warning"
                  v-if="scope.row.isAuth=='0'">未提交</el-tag>
          <el-tag type="info"
                  v-if="scope.row.isAuth=='1'">待审核</el-tag>
          <el-tag type="success"
                  v-if="scope.row.isAuth=='2'">已通过</el-tag>
          <el-tag type="danger"
                  v-if="scope.row.isAuth=='-1'">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="推荐医生"
                       width="80"
                       :formatter="formatterTip">
      </el-table-column>
      <el-table-column label="微信绑定"
                       width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.unionId == null || scope.row.unionId == '' ">
            <img width="32px"
                 height="32px"
                 src="static/images/wechat_g.png">
          </span>
          <span v-if="scope.row.unionId != null && scope.row.unionId != ''">
            <img width="32px"
                 height="32px"
                 src="static/images/wechat.png">
          </span>
        </template>
      </el-table-column>
      <el-table-column label="简介"
                       :formatter="formatterIntroduce"
                       width="200">
      </el-table-column>
      <el-table-column prop="companyDto.name"
                       label="所属公司"
                       width="100">
      </el-table-column>
      <!-- <el-table-column label="二维码"
                       width="80">
        <template slot-scope="scope">
          <el-image :src="scope.row.qrCodeUrl"
                    :preview-src-list="[scope.row.qrCodeUrl]">
          </el-image>
        </template>
      </el-table-column> -->
      <el-table-column label="创建时间"
                       width="130"
                       :formatter="formatterDate">
      </el-table-column>
      <el-table-column label="操作"
                       width="180"
                       align="center">
        <template slot-scope="scope">
          <el-button type="primary"
                     size="mini"
                     @click="showEditDoctorPage(scope.row.id)">编 辑
          </el-button>
          <el-button size="mini"
                     type="danger"
                     @click="showTipBox(scope.row.id)">删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <p align="right"
       class="mt-20">
      <el-pagination background
                     @current-change="handleCurrentChange"
                     :current-page.sync="pageIndex"
                     :page-size="pageSize"
                     layout="total, prev, pager, next"
                     :total="totalNum">
      </el-pagination>
    </p>
    <el-dialog title="医生详情"
               width="800px"
               center
               :close-on-click-modal="false"
               :visible.sync="dialogFormVisible">
      <el-form :model="doctorDetail">
        <el-form-item :label-width="formLabelWidth"
                      label="头像">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess"
                     :before-upload="beforeAvatarUpload">
            <img v-if="doctorDetail.headImageUrl"
                 :src="doctorDetail.headImageUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="登录账号">
          <el-input v-model="doctorDetail.loginName"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="用户昵称">
          <el-input v-model="doctorDetail.nickName"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="用户邀请码">
          <el-input v-model="doctorDetail.inviteCode"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="所在地">
          <el-input v-model="doctorDetail.areaName"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="办公电话">
          <el-input v-model="doctorDetail.departPhone"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="医院">
          <el-select v-model="doctorDetail.hospitalId"
                     filterable
                     remote
                     clearable
                     placeholder="请选择医院..."
                     :remote-method="remoteMethod"
                     :loading="loading">
            <el-option v-for="item in hospitalList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="科室">
          <el-select v-model="doctorDetail.departmentId">
            <el-option v-for="item in departmentList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="职称">
          <el-select v-model="doctorDetail.doctorTitleId">
            <el-option v-for="item in doctorTitles"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="性别">
          <el-radio-group v-model="doctorDetail.sex">
            <el-radio :label="0">女</el-radio>
            <el-radio :label="1">男</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="是否可以开处方">
          <el-radio-group v-model="doctorDetail.prescription">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="在线状态">
          <el-radio-group v-model="doctorDetail.isOnline">
            <el-radio :label="1">在线</el-radio>
            <el-radio :label="2">离线</el-radio>
            <el-radio :label="3">退出登录</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="用户状态">
          <el-radio-group v-model="doctorDetail.isUse">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="个人简介">
          <el-input type="textarea"
                    v-model="doctorDetail.introduce"
                    :rows="4"
                    maxlength="100"
                    show-word-limit
                    placeholder="请输入个人简介..."></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="擅长领域">
          <el-input type="textarea"
                    v-model="doctorDetail.remark"
                    :rows="4"
                    maxlength="100"
                    show-word-limit
                    placeholder="请输入擅长领域..."></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="执业证照片">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess1"
                     :before-upload="beforeAvatarUpload">
            <img v-if="doctorDetail.doctorBase.qualiUrl"
                 :src="doctorDetail.doctorBase.qualiUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth"
                      label="工作证照片">
          <el-upload class="avatar-uploader"
                     :action="imageUploadUrl"
                     :show-file-list="false"
                     :on-success="handleAvatarSuccess2"
                     :before-upload="beforeAvatarUpload">
            <img v-if="doctorDetail.doctorBase.certiUrl"
                 :src="doctorDetail.doctorBase.certiUrl"
                 class="avatar">
            <i v-else
               class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="saveData()">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  export default {
    name: "doctorList",
    data () {
      return {
        totalNum: 0,
        nickName: '',
        startTime: null,
        endTime: null,
        pageIndex: 1,
        pageSize: 10,
        loadingList: false,
        loading: false,
        loading1: false,
        hospitalList: [],
        departmentList: [],
        doctorTitles: [],
        infiniteId: 0,
        state: '',
        dialogFormVisible: false,
        tipBoxDialogVisible: false,
        formLabelWidth: '120px',
        imageUploadUrl: this.api.appUpgradeUpload.url,
        dataList: [],
        doctorDetail: {
          id: null,
          loginName: null,
          nickName: null,
          headImageUrl: null,
          isAuth: null,
          isExpert: null,
          isTip: null,
          email: null,
          departPhone: null,
          sex: null,
          hospitalId: null,
          departmentId: null,
          doctorTitleId: null,
          introduce: null,
          remark: null,
          inviteCode: null,
          areaName: null,
          isOnline: null,
          isUse: null,
          doctorBase: {
            id: null,
            qualiUrl: null,
            certiUrl: null
          }
        },
        companyId: '',
        companyList: [],
        companyFilterList: [],
        fileImportAction: this.api.department.importDoctor,
        token: JSON.parse(sessionStorage.getItem('token')),  // token
        loginId: JSON.parse(sessionStorage.getItem('id')),  // loginId
      }
    },
    methods: {
      handleQuery() {
        this.pageIndex=1
        this.initTableData()
      },
      initTableData () {
        let param = {
          nickName: this.nickName,
          startTime: this.startTime,
          endTime: this.endTime,
          pageSize: this.pageSize,
          pageIndex: this.pageIndex - 1,
          companyId: this.companyId
        };
        this.loadingList = true;
        this.post(this.api.doctorManager.list, param).then((res) => {
          if (res.data.code === '200') {
            this.loadingList = false;
            this.dataList = res.data.object;
            this.totalNum = res.data.totalNum;
          }
        });

      },
      initDoctorTitles () {
        let param = {
          pageIndex: 0,
          pageSize: 100
        };
        this.post(this.api.doctorTitle.getPageAPP, param).then((res) => {
          if (res.data.code === '200') {
            this.doctorTitles = res.data.object;
          }
        });
      },
      initDepartment () {
        this.post(this.api.department.getDepartPageApp, { "pageIndex": 0, "pageSize": 100 }).then((res) => {
          this.departmentList = res.data.object;
        });
      },

      handleCurrentChange (val) {
        this.pageIndex = val;
        this.initTableData();
      },
      // 导入医生
      uploadSuccess (response, file, fileList) {
        if (response.code === '200') {
          this.$message.error('导入成功!');
          this.initTableData();
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        };
      },
      // 文件导入格式限制
      beforeAvatarUpload (file) {
        const isType = file.type === 'application/vnd.ms-excel';
        const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        const fileType = isType || isTypeComputer;
        if (!fileType) {
          this.$message.error('导入文件只能是xls/xlsx格式！');
        }
        return fileType;
      },
      // 文件超出个数限制时的钩子
      exceedFile (files, fileList) {
        // this.$message.warning(`只能选择 ${this.limitNum} 个文件!`);
      },
      // 远程搜索参与公司
      searchMethod (query) {
        if (query !== '') {
          this.loading1 = true;
          let _this = this;
          this.post(this.api.company.companyList, {
            pageIndex: this.pageIndex - 1,
            pageSize: this.pageSize,
            name: query,
            hospitalType: '',
            status: 1
          }).then(res => {
            if (res.data.code === '200') {
              this.loading1 = false;
              _this.companyList = res.data.object;
            }
          })
          setTimeout(() => {
            this.loading1 = false;
            this.companyFilterList = this.companyList.filter(item => item.name.indexOf(query) > -1);
          }, 200)
        } else {
          this.companyFilterList = [];
        }
      },
      handleSelect (item) {
        this.companyId = item;
      },
      remoteMethod (query) {
        if (query !== '') {
          this.loading = true;
          this.post(this.api.searchHospital, { "pageSize": 20, "pageStart": 0, "name": query }).then((res) => {
            this.loading = false;
            this.hospitalList = res.data.object
          });
        } else {
          this.hospitalList = [];
        }
      },
      // 编辑
      showEditDoctorPage (id) {
        this.initDoctorTitles();
        this.initDepartment();
        this.post(this.api.doctorManager.doctorDetail, { "id": id }).then((res) => {
          if (res.data.code === '200') {
            this.doctorDetail = res.data.object;
            if (this.doctorDetail.hospitalDto) {
              this.hospitalList = [{
                id: this.doctorDetail.hospitalDto.id,
                name: this.doctorDetail.hospitalDto.name
              }];
            }
            if (this.doctorDetail.doctorBase) {
              if (!this.doctorDetail.doctorBase.certiUrl) {
                this.doctorDetail.doctorBase.certiUrl = "";
              }
              if (!this.doctorDetail.doctorBase.qualiUrl) {
                this.doctorDetail.doctorBase.qualiUrl = "";
              }
            } else {
              this.doctorDetail.doctorBase = { certiUrl: null, qualiUrl: null }
            }
            this.editDoctorPage = true;
          } else {
            this.$message({
              showClose: true,
              message: res.data.message,
              type: 'error'
            })
          }
        });
        this.dialogFormVisible = true
      },
      filterTag (value, row) {
        return row.tag === value;
      },
      // 删除
      showTipBox (id) {
        this.$confirm('确认删除？')
          .then(_ => {
            this.post(this.api.doctorManager.deleteDoctor, { "id": id }).then((res) => {
              if (res.data.code === '200') {
                this.$message.success('删除成功!');
                this.tipBoxDialogVisible = false;
                this.initTableData();
              }
            });
          })
          .catch(_ => { });
      },
      filterTag (value, row) {
        return row.tag === value;
      },
      saveData () {
        this.post(this.api.doctorManager.saveDoctor, this.doctorDetail).then((res) => {
          if (res.data.code === '200') {
            this.$message.success('保存成功!');
            this.dialogFormVisible = false;
            this.initTableData();
          }
        })
      },


      formatterExpert (row) {
        let isExpert = ["非专家", "三甲专家", "专科专家"];
        return isExpert[row.isExpert]
      },
      formatterSex (row) {
        let isSex = ["女", "男"];
        return isSex[row.sex]
      },
      formatterAuth (row) {
        let isAuth = ["待提交", "待审核", "通过"];
        if (row.isAuth === -1) {
          return "驳回"
        } else {
          return isAuth[row.isAuth];
        }
      },
      formatterTip (row) {
        let isTip = ["未推荐", "已推荐"];
        return isTip[row.isTip]
      },
      formatterIntroduce (row) {
        let introduce = row.introduce;
        if (introduce) {
          if (introduce.length > 20) {
            introduce = introduce.substring(0, 18);
            return introduce + "......";
          } else {
            return introduce;
          }
        } else {
          return ""
        }
      },
      formatterDate (row) {
        return this.commonFunction.timestampFormat(new Date(row.createTime), 'yyyy-MM-dd hh:mm')
      },
      handleAvatarSuccess (res) {
        this.doctorDetail.headImageUrl = res.object[0];
      },
      handleAvatarSuccess1 (res) {
        this.doctorDetail.doctorBase.qualiUrl = res.object[0];
      },
      handleAvatarSuccess2 (res) {
        this.doctorDetail.doctorBase.certiUrl = res.object[0];
      },

      beforeAvatarUpload (file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isLt2M;
      },
    },
    created () {
      this.initTableData();
    }
  }
</script>

<style scoped lang="scss">
  .avatar {
    width: 200px;
    height: 200px;
    display: block;
  }
  /deep/ .el-upload-list {
    display: none;
  }
</style>
